package com.tiantian.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.tiantian.cache.user.UserInfo;

public class RoleUtils {
	private final static int length = 16;
	private final static String KEY_PRE = "check";
	private final static String MENU_USE = "on";
	private final static char CHAR_AUTH_IS = '1';
	private final static char CHAR_AUTH_NOT = '0';

	/**
	 * 解析authStr
	 * 
	 * @param authStr
	 * @return
	 */
	public static Map<String, String> parseAuthoritys(String authStr, String roleId) {
		String auths = checkLen(authStr);
		Map<String, String> ret = new HashMap<String, String>();
		for (int i = 1; i <= length; i++) {
			if (i == 15 || i == 16) {// 超级管理员
				if (StringUtils.equals(UserInfo.ADMIN_ID, roleId)) {
					ret.put(KEY_PRE + i, MENU_USE);
				}
			} else {
				if (auths.charAt(i - 1) == CHAR_AUTH_IS) {
					ret.put(KEY_PRE + i, MENU_USE);
				}
			}
		}
		return ret;
	}

	/**
	 * 转换为authoritys的string
	 * 
	 * @param authMap
	 * @return
	 */
	public static String formatAuthoritys(Map<String, Object> authMap, String roleId) {
		StringBuffer ret = new StringBuffer();
		for (int i = 1; i <= length; i++) {
			if (i == 15 || i == 16) {
				if (StringUtils.equals(UserInfo.ADMIN_ID, roleId)) {
					ret.append(CHAR_AUTH_IS);
				} else {
					ret.append(CHAR_AUTH_NOT);
				}
			} else {
				Object is = authMap.get(KEY_PRE + i);
				if (is != null && MENU_USE.equals(((String[]) is)[0])) {
					ret.append(CHAR_AUTH_IS);
				} else {
					ret.append(CHAR_AUTH_NOT);
				}
			}
		}
		return ret.toString();
	}

	/**
	 * 验证格式长度
	 * 
	 * @param authStr
	 * @return
	 */
	private static String checkLen(String authStr) {
		if (StringUtils.isBlank(authStr)) {
			return appendNot(authStr, length);
		}
		String auths = authStr.trim();
		if (auths.length() < length) {
			return appendNot(authStr, length - auths.length());
		} else if (auths.length() > length) {
			return auths.substring(0, length);
		}
		return auths;
	}

	/**
	 * 补全
	 * 
	 * @return
	 */
	private static String appendNot(String authStr, int length) {
		StringBuffer buffer = new StringBuffer();
		if (StringUtils.isNotBlank(authStr)) {
			buffer.append(authStr);
		}
		for (int i = 0; i < length; i++) {
			buffer.append(CHAR_AUTH_NOT);
		}
		return buffer.toString();
	}

}
